package com.sita.linboard.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.linboard.DriverVehicle.DriverUnBindVehicleActivity;
import com.sita.linboard.R;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.driverInfo.ClearBackBean;
import com.sita.linboard.driverInfo.DriverSetInfoActivity;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.utils.BitmapUtils;
import com.sita.linboard.utils.ConstantValues;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.io.File;

import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;
/**
 * Created by Jason on 2016/9/27.
 */
public class RegisterThirdActivity extends BaseActivity implements View.OnClickListener{
    private LinearLayout back;
    private TextView head;
    private EditText vehiclelicense,vehicleframe;
    private LinearLayout allLayout;
    private Button confirmBtn;
    private RelativeLayout vehiclelayout;
    private Bitmap bitmap;
    private Uri imageUri;
    private File vehicleFile;
    private static int jumpPage;

    private ImageView vehicleImg;
    private boolean isAccountChanged;
    public enum AppState {
        FROM_LAUNCH,
        IN_FOREGROUND,
        IN_BACKGROUND,
        IN_CAMERA_PHOTO
    }
    @Override
    protected void initData() {
        head.setText("我的车辆");
        confirmBtn.setOnClickListener(this);
        vehiclelayout.setOnClickListener(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        back = bindView(R.id.img_back);
        back.setOnClickListener(this);
        back.setVisibility(View.VISIBLE);
        head = bindView(R.id.head_title);
        head.setVisibility(View.VISIBLE);
        confirmBtn = bindView(R.id.confirm_register);
        vehiclelayout = bindView(R.id.vehicle_layout);
        vehiclelicense = bindView(R.id.vehicle_license);
        vehicleframe = bindView(R.id.vehicle_frame);
        vehicleImg = bindView(R.id.vehicle_img);
        allLayout = bindView(R.id.all_third_layout);


    }

    @Override
    protected int getId() {
        return R.layout.activity_registerthird;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.confirm_register:
                    bindVehicle();
                break;
            case R.id.vehicle_layout:
                if(Build.VERSION.SDK_INT>=23) {
                    String[] mPermissionList = new String[]{Manifest.permission.CAMERA};
                    ActivityCompat.requestPermissions(RegisterThirdActivity.this, mPermissionList, 123);
                }
                showPopWindow(2);
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }
    private void bindVehicle(){

      if (vehiclelicense.getText().toString().length()==0||vehicleframe.getText().toString().length()==0){
          ToastUtils.show("输入信息为空，请确认输入正确",3);
          return;
      }
        else {
          RegisterThirdRequest request = new RegisterThirdRequest();
          request.user_id = SpUtils.getString("AccoundID",null,BaseApplication.getContext());
          if (vehiclelicense.getText().toString().length()!=0){
              request.sn_id = vehicleframe.getText().toString();
          }
          if (vehicleframe.getText().toString().length()!=0){
              request.plate_number = vehiclelicense.getText().toString();
          }
          String resStr = RestClient.getGson().toJson(request);
          TypedString string = new TypedString(resStr);
          TypedFile file =new TypedFile("vehicle",reverseimgSace());
          RestClient.getRestService().bindVehicle(string, file, new Callback<ClearBackBean>() {
              @Override
              public void success(ClearBackBean clearBackBean, Response response) {

                  if (clearBackBean.getErrorCode().equals("0")&&(int)Double.parseDouble(String.valueOf(clearBackBean.getData()))==1){
                      if (jumpPage==2){
                          ToastUtils.show("绑定车辆完成，请重新登录",3);
                          DriverLoginActivity.DriverLoginIntent(RegisterThirdActivity.this);
                      }else if (jumpPage==1){
                          ToastUtils.show("绑定车辆完成",3);
                          DriverUnBindVehicleActivity.DriverIntent(RegisterThirdActivity.this);
                      }else {
                          ToastUtils.show("绑定车辆完成",3);
                          finish();
                      }
                  }
                  else {
                      ToastUtils.show("绑定失败",3);
                      return;
                  }
              }

              @Override
              public void failure(RetrofitError error) {
                  ToastUtils.show("绑定失败，请重新绑定",3);
                  return;
              }
          });

      }
    }
    public static void RegisterThirdIntent(Context context,int jumpNumber){
        Intent intent = new Intent(context,RegisterThirdActivity.class);
        jumpPage = jumpNumber;
        context.startActivity(intent);
    }
    private void showPopWindow(final int type){
        final PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_popwindows,null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);//item是否相应点击事件
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(allLayout, Gravity.BOTTOM,0,0);
        popupWindow.update();
        Button btCam = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button btCancle = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        btCam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入相机
                clickTakePhoto(type);
                popupWindow.dismiss();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册
                clickPickFromGallery(type);
                popupWindow.dismiss();
            }
        });
        btCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }
    /**
     * 进入相机
     * @param type
     */
    private void clickTakePhoto(final int type){
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck  == PackageManager.PERMISSION_GRANTED){
            EasyImage.openCamera(this,type);
            getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
        }
        else {
            Nammu.askForPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(RegisterThirdActivity.this,type);
                    //
                    getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }
    protected void clickPickFromGallery(int type) {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this,type);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePicked(File file, EasyImage.ImageSource imageSource, int i) {
                isAccountChanged = true;
                imageUri = Uri.fromFile(file);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                /**
                 * 这段代码将图片的大小进行缩小
                 */
                BitmapFactory.decodeFile(file.toString(), options);
                // options.inSampleSize = calculateInSampleSize(options, 94, 94);
                final int height = options.outHeight;
                final int width = options.outWidth;
                options.inSampleSize = 1;
                int w = 320;
                int h = 480;
                h = w * height / width;//计算出宽高等比率
                int a = options.outWidth / w;
                int b = options.outHeight / h;
                options.inSampleSize = Math.max(a, b);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeFile(file.toString(), options);
                    vehicleImg.setImageBitmap(bitmap);
                    vehicleImg.setTag(file.getAbsolutePath());
                    LogUtils.d("3333",file.getAbsolutePath());
            }


            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                super.onImagePickerError(e, source, type);
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                super.onCanceled(source, type);
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(RegisterThirdActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap!=null){
            bitmap.recycle();
        }
        ActivityCollector.removeActivity(this);
        System.gc();
    }
    private  File  reverseimgSace(){
        String END_IMG = "vehicle_end_img";
        //   if (vehicle_end.getB)
        vehicleFile = BitmapUtils.saveBmpFile(((BitmapDrawable)vehicleImg.getDrawable()).getBitmap(),END_IMG);
        return vehicleFile;
    }
}
